package com.yiqi.liebang.feature.mine.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.DateTool;
import com.yiqi.liebang.common.util.GetJsonDataUtil;
import com.yiqi.liebang.entity.bo.JsonBean;
import com.yiqi.liebang.entity.bo.OrganizationBo;
import com.yiqi.liebang.feature.mine.contract.EnterpriseContract;
import com.yiqi.liebang.feature.mine.dependencies.enterprise.DaggerEnterpriseComponent;
import com.yiqi.liebang.feature.mine.dependencies.enterprise.EnterprisePresenterModule;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class EnterpriseCertificationActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener,
        Toolbar.OnMenuItemClickListener, EnterpriseContract.View {

    @Inject
    EnterpriseContract.Presenter mPresenter;

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rg_city)
    RadioGroup mRgCity;
    @BindView(R.id.bt_upload_image)
    ImageView mBtUploadImage;
    @BindView(R.id.rb_city_other)
    RadioButton mRbCityOther;
    @BindView(R.id.edt_organization_name)
    EditText mEdtOrganizationName;
    @BindView(R.id.edt_organization_full_name)
    EditText mEdtOrganizationFullName;
    @BindView(R.id.edt_organization_contact_name)
    EditText mEdtOrganizationContactName;
    @BindView(R.id.edt_organization_contact_position)
    EditText mEdtOrganizationContactPosition;
    @BindView(R.id.edt_organization_contact_mobile)
    EditText mEdtOrganizationContactMobile;
    @BindView(R.id.edt_organization_address)
    EditText mEdtOrganizationAddress;
    @BindView(R.id.edt_organization_contact_mail)
    EditText mEdtOrganizationContactMail;
    @BindView(R.id.tv_city_choose)
    TextView mTvCityChoose;
    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    private List<LocalMedia> selectList;
    private String uri;

    private String mCity;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_enterprise_certification;
    }

    @Override
    protected void initInjector() {
        DaggerEnterpriseComponent.builder().enterprisePresenterModule(new EnterprisePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_commit);
        initToolBar(mToolbar, "认证", true, true);
    }

    @Override
    protected void initData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        mPresenter.getorganizationCardData();
    }

    @Override
    protected void initEvent() {
        mRgCity.setOnCheckedChangeListener(this);
        mToolbar.setOnMenuItemClickListener(this);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId) {

            case R.id.rb_city_bj:
                mCity = "北京";
                mTvCityChoose.setVisibility(View.GONE);
                break;
            case R.id.rb_city_sh:
                mTvCityChoose.setVisibility(View.GONE);
                mCity = "上海";
                break;
            case R.id.rb_city_gz:
                mTvCityChoose.setVisibility(View.GONE);
                mCity = "广州";
                break;
            case R.id.rb_city_sz:
                mTvCityChoose.setVisibility(View.GONE);
                mCity = "深圳";
                break;
            case R.id.rb_city_other:
                if (isLoaded) {
                    showPickerView();
                } else {
                    T.showShort("Please waiting until the data is parsed");
                }
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(EnterpriseCertificationActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(EnterpriseCertificationActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(EnterpriseCertificationActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
            }
        }
    };

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2);
                mCity = tx;
                mTvCityChoose.setVisibility(View.VISIBLE);
                mTvCityChoose.setText(mCity);


            }
        })

                .setTitleText("城市选择")
                .setDividerColor(R.color.div_primary)
                .setLineSpacingMultiplier(2.5f)
                .setTextColorCenter(R.color.text_primary) //设置选中项文字颜色
                .setContentTextSize(15)
                .build();


        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        List<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体


        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<List<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                List<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public List<JsonBean> parseData(String result) {//Gson 解析
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }


    @OnClick(R.id.bt_upload_image)
    public void onViewClicked() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style1)
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isCamera(true)
                .enableCrop(true)// 是否裁剪
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .withAspectRatio(16, 9)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .compress(true)// 是否压缩
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .selectionMedia(selectList)// 是否传入已选图片
                .scaleEnabled(true)
                .forResult(9);//结果回调onActivityResult code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case 9:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        uri = selectList.get(i).getCutPath();
                    }
                    AM.image().bind(uri, mBtUploadImage);
                    break;
            }
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_shenhe) {
            mPresenter.organizationCertification(
                    mEdtOrganizationName.getText().toString(),
                    mEdtOrganizationFullName.getText().toString(),
                    mEdtOrganizationContactName.getText().toString(),
                    mEdtOrganizationContactPosition.getText().toString(),
                    mEdtOrganizationContactMobile.getText().toString(),
                    mEdtOrganizationContactMail.getText().toString(),
                    mCity,
                    mEdtOrganizationAddress.getText().toString(),
                    uri
            );
        }
        return false;
    }

    @Override
    public void showAuthSuccess() {
        Intent intent = new Intent(this, CommitSuccessActivity.class);
        intent.putExtra("date", DateTool.getCurTimeString());
        startActivity(intent);
        finish();
    }

    @Override
    public void showOrganizationInfoSuccess(OrganizationBo organizationBo) {
        if (organizationBo == null) return;
        if (organizationBo.getStatus() != null) {
            switch (organizationBo.getStatus()) {
//                    case 0:
////                        Intent intent = new Intent(this, CommitSuccessActivity.class);
////                        intent.putExtra("date", organizationBo.getCreateTime());
////                        startActivity(intent);
////                        finish();
//                        break;
//                    case 1:
//                        startActivity(new Intent(this, CertificationSuccessActivity.class));
//                        finish();
//                        break;
//                    case 2:
//                        startActivity(new Intent(this, CertificationFailActivity.class));
//                        break;
            }
        }
        mCity = organizationBo.getCity();
        mEdtOrganizationName.setText(organizationBo.getMechanismName());
        mEdtOrganizationFullName.setText(organizationBo.getFullName());
        mEdtOrganizationContactName.setText(organizationBo.getContactsName());
        mEdtOrganizationContactPosition.setText(organizationBo.getContactsPosition());
        mEdtOrganizationContactMobile.setText(organizationBo.getContactsPhone());
        mEdtOrganizationContactMail.setText(organizationBo.getEmail());
        mEdtOrganizationAddress.setText(organizationBo.getRegion());
        AM.image().bind(organizationBo.getBusinessLicense(), mBtUploadImage);
        if (!TextUtils.isEmpty(mCity)) {
            if (mCity.equals("北京")) {
                mRgCity.check(R.id.rb_city_bj);
                mTvCityChoose.setVisibility(View.GONE);
            } else if (mCity.equals("上海")) {
                mRgCity.check(R.id.rb_city_sh);
                mTvCityChoose.setVisibility(View.GONE);
            } else if (mCity.equals("广州")) {
                mRgCity.check(R.id.rb_city_gz);
                mTvCityChoose.setVisibility(View.GONE);
            } else if (mCity.equals("深圳")) {
                mRgCity.check(R.id.rb_city_sz);
                mTvCityChoose.setVisibility(View.GONE);
            } else {
                mRgCity.check(R.id.rb_city_other);
                mTvCityChoose.setVisibility(View.VISIBLE);
                mTvCityChoose.setText(mCity);
            }
        }

    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }


    @OnClick(R.id.tv_city_choose)
    public void onViewsClicked() {
        if (isLoaded) {
            showPickerView();
        } else {
            Logger.d("Please waiting until the data is parsed");
        }
    }
}
